package com.atguigu.gulimall.cart.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

//开启ThreadPoolConfigProperties的配置，需要用的类写了@Component就不用开启了
//@EnableConfigurationProperties(ThreadPoolConfigProperties.class)
//getMaxSize需要看是IO密集型还是CPU密集型，如果是CPU密集型则数量为CPU核数+1 IO密集型则为CPU核数*2或则CPU核数/(1-(0.8~0.9之间阻塞系数))
//拒绝策略，超过线程池最高上限数(最大线程数+阻塞队列数)后进行拒绝，默认为抛出异常，其余为不抛异常也不拒绝，返回给调用者、直接拒绝、选择等待时间最长的进行抛弃
@Configuration
public class MyThreadConfig {
    @Autowired
    ThreadPoolConfigProperties poolConfigProperties;

    @Bean
    public ThreadPoolExecutor threadPoolExecutor(){
        //LinkedBlockingDeque默认最大为泛型的值
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(poolConfigProperties.getCoreSize(),
                poolConfigProperties.getMaxSize(),
                poolConfigProperties.getKeepAliveTime(),
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(100000),
                Executors.defaultThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
        return threadPoolExecutor;
    }
}
